import router, { resetRouter } from "./router";
import { storeToRefs } from "pinia";
import store, { useUserStore, usePermissionStore } from "./stores";
const allowList = ["/login", "/404"];
const notFount = { path: "/:pathMatch(.*)*", redirect: "/404" };
router.beforeEach((to, from, next) => {
    const userStoreData = useUserStore(store);
    const permissionStoreData = usePermissionStore(store);
    const token = localStorage.getItem("ACCESS_TOKEN");
    if (token) {
        if (to.path === "/login") {
            next("/");
        } else {
            const { roles, menus } = storeToRefs(userStoreData);
            const { addRoutes } = storeToRefs(permissionStoreData);
            const isReload = localStorage.getItem("IS_RELOAD");
            if (menus.value.length) {
                if (isReload) {
                    localStorage.removeItem("IS_RELOAD");
                    permissionStoreData
                        .generateRoutes(roles.value)
                        .then((res: any) => {
                            resetRouter(); // 重置路由
                            res.push(notFount);
                            res.forEach((route: any) => {
                                router.addRoute(route); // 添加动态路由
                            });
                            console.log(res, "最终res----------");
                            // router.addRoute(notFount); // 添加404
                            next({ ...to, replace: true });
                        });
                } else {
                    next();
                }
            } else {
                permissionStoreData
                    .generateRoutes(roles.value)
                    .then((res: any) => {
                        resetRouter(); // 重置路由
                        res.push(notFount);
                        res.forEach((route: any) => {
                            router.addRoute(route); // 添加动态路由
                        });
                        next({ ...to, replace: true });
                    });
            }
        }
    } else {
        if (allowList.includes(to.path)) {
            next();
        } else {
            next("/login");
        }
    }
});
